package top.cyuw.simplerpc.registry.memory;

import top.cyuw.simplerpc.config.RpcServiceConfig;
import top.cyuw.simplerpc.exception.RpcException;
import top.cyuw.simplerpc.registry.ServiceRegistry;

import java.net.InetSocketAddress;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author chen
 * @date 2023/3/16 21:10
 */
public class MemoryServiceRegistry implements ServiceRegistry {

    private final Map<String, Object> serviceMap;

    public MemoryServiceRegistry() {
        serviceMap = new ConcurrentHashMap<>();
    }

    @Override
    public void registerService(RpcServiceConfig serviceConfig, InetSocketAddress address) {
        Object service = serviceConfig.getService();
        Object result = serviceMap.putIfAbsent(serviceConfig.getFullServiceName(), service);
        if (result != null && service != result) {
            throw new RpcException("service name conflict: " + serviceConfig.getFullServiceName());
        }
    }

    @Override
    public Object getService(String serviceName) {
        return serviceMap.get(serviceName);
    }

    @Override
    public void clear() {
        serviceMap.clear();
    }
}
